from pprint import pprint

from core.repositories._base import CRUDRepository
from core.services import get_db, get_vm_conn
from eve import utils
from eve.models.libvirt_models.domain import Domain, Interface
from eve.models.virtual_machine_instance import VirtualMachineInstance
from eve.validators.virtual_machine_interface import (
    VirtualMachineInterfaceCreatingValidator as CreatingValidator,
    VirtualMachineInterfacePartialUpdatingValidator as PartialUpdatingValidator,
)


class VirtualMachineInterfaceRepository(CRUDRepository):
    def create(self, payload: CreatingValidator):
        virtual_machine_instance_id = payload.virtual_machine_instance_id
        # 从 数据库里根据id，取出name

        virtual_machine_instance = VirtualMachineInstance.find_or_fail(virtual_machine_instance_id)
        domain_name = virtual_machine_instance.domain_name
        name = virtual_machine_instance.name
        # name = 'centos7.0'
        client = get_vm_conn()
        conn = next(client)
        domain = conn.lookupByName(name)
        domain_xml = domain.XMLDesc()

        domain: Domain = Domain.from_xml(domain_xml)
        domain.devices.interfaces.append(Interface())  
        conn.defineXML(domain.to_xml())

        # 去虚拟里设置IP，虚拟器启动了
        ipv4 = payload.ipv4
        netmask = payload.netmask
        utils.config_ipv4(domain_name, ipv4, netmask, 'eth0')

        return super().create(payload)

    def partial_update(self, id, payload: PartialUpdatingValidator):
        virtual_machine_instance_id = payload.virtual_machine_instance_id
        ipv4 = payload.ipv4
        netmask = payload.netmask

        client = get_db()
        db = next(client)
        virtual_machine_instance: VirtualMachineInstance = db.query(VirtualMachineInstance).filter(
            VirtualMachineInstance.id == virtual_machine_instance_id).first()
        if not virtual_machine_instance:
            return None

        domain_name = virtual_machine_instance.domain_name
        utils.config_ipv4(domain_name, ipv4, netmask, 'eth0')

        return super().partial_update(id, payload)


